package unilearn.da;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.naming.*;
import javax.sql.DataSource;

/**
 * @author Ben Morrall, 4158768
 * @version 0.2, May 14 2008, Refactored Code, blm
 */
public abstract class DABase
{
	private static Connection conn = null;
	private static String connString = "jdbc:derby:unilearndb";
	private static boolean RUN_IN_TOMCAT = true;

	public static Connection getConn() throws SQLException
	{
		// This is how a DB connection should be obtained when deployed within Tomcat
		// It uses the Tomcat's builtin support for connection pooling. Unfortunately
		// it won't work in a normal Java environment.
		if (RUN_IN_TOMCAT)
		{
			try
			{
				// Obtain our environment naming context;
				Context initCtx = new InitialContext();
				Context envCtx = (Context) initCtx.lookup("java:comp/env");

				// Look up our data source
				DataSource ds = (DataSource) envCtx.lookup("jdbc/unilearndb");

				// Allocate and use a connection from the pool
				conn = ds.getConnection();
			}
			catch (NamingException e)
			{
				throw new Error(e);
			}
		}
		else
		{
			if (conn == null)
			{
				try
				{
					Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
				}
				catch (Exception e)
				{
					throw new Error(e);
				}

				conn = DriverManager.getConnection(connString + ";create=true");
			}
		}

		return conn;
	}

	public static void setConnString(String newConnString)
	{
		connString = newConnString;
	}

	/**
	 * Shutdowns the Derby Database so it can be rebuild Prevents Resource Locking
	 */
	public static void shutdown()
	{
		try
		{
			if (conn != null) conn.close();
		}
		catch (SQLException e)
		{
			System.err.println("Connection Close: " + e.getMessage());
		}
		conn = null;
		try
		{
			DriverManager.getConnection(connString + ";shutdown=true");
		}
		catch (SQLException e)
		{
			// Error is expected, welcome it!!!
		}
	}

	/**
	 * Prevent Instances of DABase
	 */
	protected DABase()
	{
	}
}
